/*
 * MobileBehaviour.java
 *
 * Created on 12 de Fevereiro de 2008, 01:06
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package br.ufal.ic.mobile.behaviours;

import jade.core.AID;
import jade.core.Agent;
import jade.core.PlatformID;
import jade.core.behaviours.CyclicBehaviour;
import jade.core.behaviours.SimpleBehaviour;
import jade.domain.FIPAAgentManagement.DFAgentDescription;
import jade.domain.FIPAAgentManagement.ServiceDescription;
import jade.lang.acl.ACLMessage;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Properties;
import java.util.Vector;

/**
 *
 * @author Raphael
 */
public class MobileBehaviour extends SimpleBehaviour {
    private boolean done;
    private int state;
    private int hopcounter;
    private Vector hosts;
    private String arg;
    
    /**
     * Creates a new instance of MobileBehaviour
     */
    public MobileBehaviour(String arg, int hopcounter, Vector hosts) {
        this.done = false;
        this.state = 0;
        this.hopcounter = hopcounter;
        this.arg = arg;
        this.hosts = hosts;
    }

    public void action() {
        switch(this.state){
        case 0:
            if (this.hosts.size() == this.hopcounter) {
//                myAgent.addBehaviour(new SEHBehaviour(this.arg));
                ACLMessage sendMessage = new ACLMessage(ACLMessage.INFORM);            
                sendMessage.setContent("[SEH]#"+this.arg);
                sendMessage.addReceiver(myAgent.getAID());
                myAgent.send(sendMessage);
            } else {
                if (this.hosts.get(this.hopcounter).equals(getHostOfAgent(myAgent))) {
                    this.hopcounter++;
                } else {
                    System.out.println("\n\nMovendo para "+this.hosts.get(this.hopcounter));

                    AID aid = new AID("ams@"+(String)this.hosts.get(this.hopcounter)+":1099/JADE",true);
                    aid.addAddresses("http://"+(String)this.hosts.get(this.hopcounter)+":7778/acc");
                    PlatformID dest = new PlatformID(aid);

                    this.state++;

                    myAgent.doMove(dest);                    
                }
            }
            
            break;
        case 1:
            this.done = true;
            myAgent.addBehaviour(new SearchBehaviour(this.arg, this.hopcounter, this.hosts));
        }
    }

    public boolean done() {
        return this.done;
    }    
    
    private String getHostOfAgent(Agent a) {
        String hap = a.getHap();
        String[] aux = hap.split(":");
        
        return aux[0];
    }
}